package marchsoft.modules.tiku.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import marchsoft.base.PageVO;
import marchsoft.enums.ResultEnum;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.tiku.entity.ESafeType;
import marchsoft.modules.tiku.entity.dto.AddSafeTypeDto;
import marchsoft.modules.tiku.entity.dto.ESafeTypeDto;
import marchsoft.modules.tiku.entity.dto.SafeTypeQueryCriteria;
import marchsoft.modules.tiku.mapper.ESafeTypeMapper;
import marchsoft.modules.tiku.service.IESafeTypeService;
import marchsoft.base.BasicServiceImpl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import marchsoft.modules.tiku.service.mapstruct.SafeTypeMapStruct;
import marchsoft.utils.FileUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* <p>
* 安全类别 服务实现类
* </p>
*
* @author zsy
* @since 2022-03-29
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "safetype")
public class ESafeTypeServiceImpl extends BasicServiceImpl<ESafeTypeMapper, ESafeType> implements IESafeTypeService {

    private final ESafeTypeMapper eSafeTypeMapper;
    private final SafeTypeMapStruct safeTypeMapStruct;

    @Override
    @Cacheable(key = "'names:'+#criteria.name + #pageVO.size +#pageVO.current +#pageVO.orders")
    public IPage<ESafeType> getAll(SafeTypeQueryCriteria criteria, PageVO pageVO) {
        LambdaQueryWrapper<ESafeType> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.like(ESafeType::getName,criteria.getName());
        IPage<ESafeType> eSafeTypeIPage=eSafeTypeMapper.selectPage(pageVO.buildPage(),null);
//        IPage<ESafeType> eSafeTypeIPage=eSafeTypeMapper.getAllPage(page);
        return eSafeTypeIPage;
    }

    @Override
    @CacheEvict(key = "'all'",allEntries = true)
    public int deleteByIds(Set<Long> ids) {
        return eSafeTypeMapper.deleteType(ids);
    }

    @Override
    @CacheEvict(key = "'all'" ,allEntries = true)
    public void addSafeType(AddSafeTypeDto safeTypeDto) {
        //判断前端传来的分类名称是否重复
        LambdaQueryWrapper<ESafeType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ESafeType::getName,safeTypeDto.getName());
//        ESafeType type=this.getOne(queryWrapper);
        ESafeType type=eSafeTypeMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNotNull(type)){
            throw new BadRequestException(ResultEnum.TYPE_NAME_IS_EXIST);
        }
        //判断前端传来的分类排序是否重复
        LambdaQueryWrapper<ESafeType> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(ESafeType::getSeqNum,safeTypeDto.getSeqNum());
        ESafeType eSafeType2=eSafeTypeMapper.selectOne(queryWrapper1);
        if(ObjectUtil.isNotNull(eSafeType2)){
            throw new BadRequestException(ResultEnum. TYPE_SHOW_IS_EXIST);
        }
       ESafeType eSafeType= safeTypeMapStruct.addDtoToEntity(safeTypeDto);
        //
        //新增
        int i=eSafeTypeMapper.insert(eSafeType);
        if(i<1){
            throw  new BadRequestException(ResultEnum.INSERT_OPERATION_FAIL);
        }


    }

    @Override
    @CacheEvict(key = "'all'",allEntries = true)
    public void updateType(ESafeType eSafeType) {
        if(ObjectUtil.isNull(eSafeType.getId())){
            throw new BadRequestException(ResultEnum.BAD_REQUEST);
        }
        ESafeType byId =this.getById(eSafeType.getId());
        if(!byId.getSeqNum().equals(eSafeType.getSeqNum())){
            LambdaQueryWrapper<ESafeType> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(ESafeType::getSeqNum,eSafeType.getSeqNum());
            ESafeType eSafeType2=eSafeTypeMapper.selectOne(queryWrapper1);
            if(ObjectUtil.isNotNull(eSafeType2)){
                 throw new BadRequestException(ResultEnum. TYPE_SHOW_IS_EXIST);
             }
        }
        int i=eSafeTypeMapper.updateById(eSafeType);
        if(i<1){
            throw  new BadRequestException(ResultEnum.UPDATE_OPERATION_FAIL);
        }
    }

    @Override
    @CacheEvict(key = "'all'",allEntries = true)
    public void updateStatus(ESafeType eSafeType) {
        int i=eSafeTypeMapper.updateStatus(eSafeType);
        if(i<1){
            throw new BadRequestException(ResultEnum.UPDATE_OPERATION_FAIL);
        }
    }

    @Override
    @Cacheable(key = "'name'")
    public List<ESafeTypeDto> getAllName(ESafeType eSafeType) {
        //状态为显示，没有被删除的
        LambdaQueryWrapper<ESafeType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ESafeType::getIsShow,1);
        List<ESafeType> eSafeTypes=eSafeTypeMapper.selectList(queryWrapper);
        List<ESafeTypeDto> eSafeTypeDtos=safeTypeMapStruct.entityToDto(eSafeTypes);
//        List<ESafeTypeDto> eSafeTypeDtos= new ArrayList<>();
//        for(ESafeType eSafeType1:eSafeTypes){
//            ESafeTypeDto  eSafeTypeDto=new ESafeTypeDto();
//            eSafeTypeDto.setId(eSafeType1.getId());
//            eSafeTypeDto.setName(eSafeType1.getName());
//            eSafeTypeDtos.add(eSafeTypeDto);
//        }
        return  eSafeTypeDtos;
 //       另一种方法：使用自己写的sql语句
//        return eSafeTypeMapper.getAllName(eSafeType);
    }

    @Override
    public List<ESafeType> getFront(ESafeType eSafeType) {
        return eSafeTypeMapper.getFront(eSafeType);
    }

    @Override
    public void download(List<ESafeType> eSafeTypeList, HttpServletResponse response) {
        if (CollectionUtil.isEmpty(eSafeTypeList)) {
            throw new BadRequestException(ResultEnum.FILE_DOWNLOAD_FAIL_NOT_DATA);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for(ESafeType eSafeType:eSafeTypeList){
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("分类名称",eSafeType.getName());
            map.put("分类简称",eSafeType.getForShort());
            map.put("分类图片",eSafeType.getPicPath());
            map.put("分类代码",eSafeType.getRooterPath());
            map.put("题库图标",eSafeType.getRepositoryPath());
            map.put("分类排序",eSafeType.getSeqNum());
            map.put("状态",eSafeType.getIsShow()? "启用" : "禁用");
            map.put("创建日期",eSafeType.getCreateTime() == null ? null : LocalDateTimeUtil.format(eSafeType.getCreateTime()
                    , DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        }
        try {
            FileUtils.downloadExcel(list, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

